#!/bin/bash

#------------------------------------------------------
COLOR_ERROR="\e[38;5;198m"
COLOR_NONE="\e[0m"
COLOR_SUCC="\e[92m"

PRG="$0"

while [ -h "$PRG" ]
do
        ls=`ls -ld "$PRG"`
        link=`expr "$ls" : '.*-> \(.*\)$'`
        if expr "$link" : '/.*' > /dev/null; then
                PRG="$link"
        else
                PRG=`dirname "$PRG"`/"$link"
        fi
done

PRGDIR=`dirname "$PRG"`

BASEDIR=`cd "$PRGDIR" >/dev/null; pwd`
ISERVERDIR=`cd "$BASEDIR"/../../ >/dev/null; pwd`
BAKLOG="$BASEDIR/build/ugobak.log"

check_pkgname(){
    while [ 1 == 1 ]
    do
        read -p "Enter NewUGO URL or LocalPath: " path
        re='tar.gz$'
        if [[ $path =~ $re ]] ; then
            break;  
        else
            echo -e "${COLOR_ERROR}Invalid PkgName. Please input a *.tar.gz path or url.${COLOR_NONE}"
        fi
    done 
    
    read -p "将用 ${path##*/} 替换 $ISERVERDIR 中的UGO，是否继续？[Y/n]" has_record

    if ! [[ "$has_record" = "Y" || "$has_record" = "" ]] ;then
        exit
    fi
}

prepare_oldugo(){
    if [ -r "$BASEDIR"/../../bin/setenv.sh ]
    then
      cd "$BASEDIR"/../../bin
      . "$BASEDIR"/../../bin/setenv.sh
      cd -
    fi
}

call_ant_exec(){
    "$BASEDIR"/bin/ant -f "$BASEDIR"/replace-ugo.xml -Dnewugo_url=$path -S replacelinux
}
restore(){
    echo "*** Stating restore... ***"
    a=()
    n=0
    while read line
    do
      let n=n+1;
      a[$n]=$line
      echo $n: ${a[$n]}    
    done<$BAKLOG;     
    while [ 1 == 1 ]
    do
        read -p "Select the bak to restore[1-$n]: " record
        if [[ $record == x ]] ; then
            exit  
        elif [[ "$record" == "" ]] ; then
            continue
        elif [[ "${a[$record]}" == "" ]] ; then
            echo -e "${COLOR_ERROR}num wrong, record not exist, enter 'x' to exit.${COLOR_NONE}"
        elif [[ "${a[$record]}" != "" ]] ; then
            "$BASEDIR"/bin/ant -f "$BASEDIR"/replace-ugo.xml -Drecord="${a[$record]}" -S restore     
            echo "*** Restore finished. ***"
            break;
        fi          
      
    done     
}


init(){
    OIFS=$IFS  # Save the current IFS (Internal Field Separator)
    IFS=','    # New IFS
    
    read -p "0(default) to replase, 1 to restore:" opr
    if [[ $opr == 1 ]] ; then
        restore  
    else
        check_pkgname
        prepare_oldugo
        call_ant_exec       
    fi    
   
    IFS=$OIFS  # Restore the IFS
}

init
